<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" :rules="queryrule" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="部门" prop="deptId">
        <treeselect v-model="queryParams.deptId" :options="deptOptions" :disable-branch-nodes="false" :show-count="true"
                    size="small"
                    :default-expand-level="1"
                    style="width: 240px"
                    placeholder="请选择部门"/>
      </el-form-item>

      <el-form-item label="员工姓名" prop="userId" >
        <el-select v-model="queryParams.userId" placeholder="请输入用户名" clearable filterable remote :remote-method="queryUserByName"  :loading="loading">
          <el-option v-for="item in userOptions" :key="item.id" :label="item.label" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="月份"  >
        <MonthPicker @change="chageDate" lang="zh" :default-month="queryParams.month"></MonthPicker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据列表 -->
      <el-table ref="form" @cell-mouse-enter="cellEnter" @cell-mouse-leave="cellLeave"
                @cell-click="cellClick" border :height=400 v-loading="loading" :data="dataList">
        <el-table-column show-tooltip-when-overflow fixed=left align="center" label="用户名" prop="nickName" />
        <el-table-column show-tooltip-when-overflow align="center" v-for="item in days" :key="'' + item" :label="item + '号'" :prop="'clockTime'+item" :column-key="''+item" :id="'cell_'+item" />
        <el-table-column fixed=right label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" >清除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                  @pagination="getList"/>

    <!-- 对话框(班次)   el-form-item 打卡时间的  prop="clockTimeStart" 先拿 掉 -->
    <el-dialog :title="title" :visible.sync="open" id="punchDialog" width="500px" append-to-body>

      <div v-if="open">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item :label="'打卡时间' + item.punchSort" v-for="(item, index) in form.punchesOfDay" :key="''+index" >
            <el-time-picker clearable size="small" style="width: 200px" v-model="item.clockTimeStart" type="time"
                            value-format="HH:mm:ss" format="HH:mm:ss"  placeholder="选择打卡时间" :picker-options="pickerOptions" />
            <el-time-picker clearable size="small" style="width: 200px" v-model="item.clockTimeEnd" type="datetime"
                            value-format="HH:mm:ss" format="HH:mm:ss"  placeholder="选择打卡时间" :picker-options="pickerOptions" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {listPunchOfDept, punchhelpAdd} from "@/api/business/punchhelp";
import {listUserLikeName} from "@/api/selfcom/user";

import {getCountDays} from "@/api/common/commonquery";
import {treeselect} from "@/api/selfcom/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

import {getMonthOrDefultThisMonth} from "@/utils/index";


import {MonthPicker} from '@/views/components/wowmonthpicker/src/index'
import {renderHoliday} from "@/api/business/holiday";


export default {
  name: "PunchHelp",
  components: { Treeselect, MonthPicker },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,

      days: 0,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 月排班表格数据
      dataList: [],
      orignDataList: [],
      pickerOptions: {
        // disabledDate(time) {
        //   return true;
        // }
      },
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: [],
      userOptions: [],
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: undefined,
        deptId: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          {required: true, message: "用户ID不能为空", trigger: "blur"}
        ]
      },
      // 表单校验
      queryrule: {
        deptId: [
          {required: true, message: "部门不能为空", trigger: "blur"}
        ]
      }
    };
  },
  created() {
    this.queryParams.month = getMonthOrDefultThisMonth();
    this.days = getCountDays();
    this.getTreeselect();
    this.getList();
  },
  methods: {
    /** 查询月排班列表 */
    getList() {
      this.loading = true;
      this.dataList = [];
      this.orignDataList = [];

      let month = getMonthOrDefultThisMonth(this.queryParams.yearMonth);

      this.days = getCountDays(month);
      listPunchOfDept(this.queryParams).then(response => {
        this.total = response.total;
        this.loading = false;
        if(response.rows.length > 0) {
          this.initCellsName(response.rows);
        }

      });
      renderHoliday(this);
    },

    chageDate(date) {
      this.queryParams.yearMonth = date.year + '-' + date.monthIndex;
      this.queryParams.month = date.monthIndex;
    },

    initCellsName(list) {
      this.orignDataList = list;
      list.forEach(single => {
        let data = {};
        data.userId = single.userId;
        data.nickName = single.nickName;
        let punches = single.punches;
        if(!! punches) {
          for (let i = 0; i < punches.length; i++) {
            let punch = punches[i]
            let dayOfMonth = punch.dayOfMonth;
            let punchesOfDay = punch.punchesOfDay;
            if(!! punchesOfDay) {
              console.log("punchesOfDay getList ", JSON.stringify(punchesOfDay))
              let clockTimes = punchesOfDay.map(tmp => {
                let formatedStart = tmp.clockTimeStart;
                let formatedEnd = tmp.clockTimeEnd;
                if(! formatedStart) {
                  formatedStart = "?"
                }
                if(! formatedEnd) {
                  formatedEnd = "?"
                }
                 // return parseTime(formated, "hh:mm")
                return formatedStart + " ~ " + formatedEnd;
              });
              data["clockTime"+ punch.dayOfMonth] = clockTimes.join("\n");
            }

          }
        }
        this.dataList.push(data)
      })
    },

    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;

        this.queryParams.deptId = this.deptOptions[0].id;
        // console.log("this.queryParams.deptId", JSON.stringify(this.deptOptions))
      });
    },
    /** 查询人 */
    queryUserByName(userName) {
      listUserLikeName(userName).then(response => {
        this.userOptions = response.rows;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      // this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        userId: undefined,
        yearMonth: undefined,
        clockTimeStart: undefined,
        dayOfMonth: undefined,
        dayOfWeek: undefined,
        deleted: undefined,
        creator: undefined,
        updater: undefined,
        createTime: undefined,
        updateTime: undefined,
        tenantId: undefined
      };
      this.resetForm("form");

      this.dataList = [];
      this.orignDataList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },

    /** 鼠标经过 */
    cellEnter(row, column, cell, event) {

      this.defaultCellBackground = cell.style.backgroundColor;
      cell.style.backgroundColor = "#44A3BB";
    },
    /** 鼠标离开 */
    cellLeave(row, column, cell, event) {
      cell.style.backgroundColor = this.defaultCellBackground;
    },

    /** 点击格子选中 user 或者记录 id */
    cellClick(row, column, cell, event) {
      this.form.punchesOfDay = [];
      this.aimId = row.id;
      this.aimUserId = row.userId;
      this.form.dayOfMonth = column.columnKey; // 其实是 dayOfMonth 填充进去的

      this.form.punchesOfDay = this.findPunchesOfDay(this.aimUserId, this.form.dayOfMonth);
      console.log("this.form.punchesOfDay", JSON.stringify(this.form.punchesOfDay))
      // 对话框定位
      this.open = true;
      this.title = "代 [" + row.nickName + "] 打 [" + column.label + "] 的卡";

    },

    /**
     * 根据 userId 去原始 dataList 中寻找到原始的数据
     * @param row
     * @returns {*|null}
     */
    findPunchesOfDay: function (userId, dayOfMonth) {
      let filtered = this.orignDataList.filter((item) => {
        if(item.userId == userId) {
          return true;
        }
      });
      if(!! filtered ) {
        let originRow = filtered[0];
        let punchesOfDay = this.extractPunchOfDay(originRow, dayOfMonth);
        return punchesOfDay;
      } else {
        return null;
      }
    },

    extractPunchOfDay: function (originRow, dayOfMonth) {
      let punchesOfDay = [];
      if(!! originRow) {
        let punches = originRow.punches;
        // console.log("try find dayOfMonth ", dayOfMonth, " from ", JSON.stringify(punches))
        if(!! punches) {
          let filtered = punches.filter((item) => {
            if(item.dayOfMonth == dayOfMonth) {
              return true;
            }
          });

          if(!! filtered ) {
            let punch = filtered[0];
            if(!! punch) {
              punchesOfDay = punch.punchesOfDay;
            }
          }

        }
      }

      // 库里面如果没存的，就填充一组空的
      for (let i = 1; i <= 1; i++) {
        let existPunch = punchesOfDay.some(punch => punch.punchSort == i);
        console.log("是否存在： ", i, existPunch);
        if(!existPunch) {
          // let now = new Date();
          // now.setDate(dayOfMonth);
          // let formated = formatDate(now);

          punchesOfDay.push({
            "punchSort": i,
            // "clockTimeStart": formated,
            // "clockTimeEnd": formated
          });
        }
      }

      punchesOfDay.sort((a, b) => a.punchSort - b.punchSort);
      return punchesOfDay;
    },

    /** 提交按钮 */
    submitForm: function () {
      let $form = this.form;
      $form.yearMonth = this.queryParams.yearMonth; // 往 form 中写 userId
      $form.id = this.aimId; // 往 form 中写 userId
      $form.userId = this.aimUserId; // 往 form 中写 userId

      // console.log("submit $form ", JSON.stringify($form))

      this.$refs["form"].validate(valid => {
        if (valid) {
          punchhelpAdd(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }
          });

        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除月排班编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delMonthschedule(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(function () {
      });
    }


  }
};
</script>
